package com.junzhiit.nengji.shop.dao.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import com.bainaeco.framework.base.dao.AbstractBaseDAO;
import com.bainaeco.framework.common.jdbc.StatementParameter;
import com.bainaeco.framework.enums.IsDelete;
import com.junzhiit.nengji.shop.dao.LogisticsDAO;
import com.junzhiit.nengji.shop.model.Logistics;

@Repository
public class LogisticsDAOImpl extends AbstractBaseDAO<Logistics> implements LogisticsDAO {

	@Override
	public List<Logistics> findAll(int pageNumber, int maxPageRow, Logistics logistics) {
		StringBuffer sql = new StringBuffer();
		sql.append("select * from `logistics` where is_delete=?");

		StatementParameter params = new StatementParameter();
		params.setInt(IsDelete.NO.toIntValue());

		if (StringUtils.isNotBlank(logistics.getName())) {
			sql.append(" and name like ?");
			params.setString("%" + logistics.getName() + "%");
		}

		sql.append(" order by sort desc");

		return queryForPagingList(sql.toString(), Logistics.class, params, pageNumber, maxPageRow);
	}

	@Override
	public Integer getTotalCount(Logistics logistics) {
		StringBuffer sql = new StringBuffer();
		sql.append("select count(id) from `logistics` where is_delete=?");

		StatementParameter params = new StatementParameter();
		params.setInt(IsDelete.NO.toIntValue());

		if (logistics != null) {
			if (StringUtils.isNotBlank(logistics.getName())) {
				sql.append(" and name like ?");
				params.setString("%" + logistics.getName() + "%");
			}
		}

		return queryForInt(sql.toString(), params);
	}

	@Override
	public Integer getMaxSort() {
		String sql = "select max(sort) from `logistics` where 1 = 1";
		String str = queryForString(sql.toString());
		if (StringUtils.isNotBlank(str)) {
			return Integer.valueOf(str);
		}
		return 0;
	}

	@Override
	public Integer getCodeExist(String code) {
		StatementParameter params = new StatementParameter();
		StringBuffer sql = new StringBuffer();

		sql.append("select count(code) from `logistics` where 1 = 1");

		if (StringUtils.isNotBlank(code)) {
			sql.append(" and code=?");
			params.setString(code);
		}

		return queryForInt(sql.toString(), params);
	}

	@Override
	public Integer getNameExist(String name) {
		StatementParameter params = new StatementParameter();
		StringBuffer sql = new StringBuffer();

		sql.append("select count(*) from `logistics` where is_delete=?");
		params.setInt(IsDelete.NO.toIntValue());

		if (StringUtils.isNotBlank(name)) {
			sql.append(" and name=?");
			params.setString(name);
		}

		return queryForInt(sql.toString(), params);
	}

	@Override
	public List<Logistics> getList() {
		String sql = "select * from `logistics` where is_delete =? order by sort desc";
		StatementParameter params = new StatementParameter();
		params.setInt(IsDelete.NO.toIntValue());
		return super.queryForList(sql.toString(), Logistics.class,params);
	}

}
